package com.icesoft.xsnow.oauth.config;

import com.icesoft.xsnow.common.core.constant.SecurityConstants;
import com.icesoft.xsnow.common.security.dto.XSnowUser;
import com.icesoft.xsnow.oauth.service.ConsumerTokenServicesImpl;
import com.icesoft.xsnow.oauth.service.XsnowClientDetailsService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: xsnow
 * @description: 认证中心基础配置 1. 开启认证中心 2. 配置客户端应用
 * @author: xuefeng.gao
 * @create: 2019-05-10 11:11
 **/
@Configuration
@EnableAuthorizationServer
@AllArgsConstructor
public class AuthorizationServerConfiguration
		extends AuthorizationServerConfigurerAdapter {

	@Resource
	private DataSource dataSource;


	/**
	 * 注入authenticationManager
	 * 来支持 password grant type
	 */
	@Autowired
	private AuthenticationManager authenticationManager;

	/**
	 * 配置客户端
	 **/
	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		XsnowClientDetailsService clientDetailsService = new XsnowClientDetailsService(dataSource);
		clients.withClientDetails(clientDetailsService);
	}

	/**
	* 配置端点
	 * 1. 配置令牌存储
	 * 2. 配置令牌增强 (将XSnowUser写入Princp)
	 * 2. 配置客户端服务
	**/
	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		endpoints
				.tokenStore(tokenStore())
				.tokenEnhancer(tokenEnhancer())
				.authenticationManager(authenticationManager)   //注入authenticationManager来支持password模式
				.allowedTokenEndpointRequestMethods(HttpMethod.POST,HttpMethod.GET)  //  password模式 支持 Get 调用 Token URL , 用于Swagger的认证
				.pathMapping("/oauth/confirm_access", SecurityConstants.OAUTH_APPROVAL_CONFIRM_URL)
				.setClientDetailsService(clientDetailsService());

	}

	@Override
	public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
//		super.configure(security);
		security
				.tokenKeyAccess("permitAll()")
//				.checkTokenAccess("permitAll()")
				.allowFormAuthenticationForClients();

	}


	/********************************************************************************************/

	/**
	* 定义令牌存储方式
	**/
	@Bean
	public TokenStore tokenStore(){
		return new InMemoryTokenStore();
	}

	/**
	* 定义令牌注销方式
	**/
	@Bean
	public ConsumerTokenServices consumerTokenServices(TokenStore tokenStore){
		return new ConsumerTokenServicesImpl(tokenStore);
	}


	/**
	 * 定义客户端服务方式
	 **/
	public ClientDetailsService clientDetailsService(){
//		return new InMemoryClientDetailsService();
		return new XsnowClientDetailsService(dataSource);
	}
/*
	@Bean
	@Primary
	@ConfigurationProperties(prefix = "spring.datasource")
	public DataSource dataSource() {
		// 配置数据源（注意，我使用的是 HikariCP 连接池），以上注解是指定数据源，否则会有冲突
		return DataSourceBuilder.create().build();
	}*/

	/**
	 * token增强，客户端模式不增强。
	 *
	 * @return TokenEnhancer
	 */
	@Bean
	public TokenEnhancer tokenEnhancer() {
		return (accessToken, authentication) -> {
			//用户信息增强
			final Map<String, Object> userinfo = new HashMap<>(8);
			XSnowUser xSnowUser = (XSnowUser) authentication.getUserAuthentication().getPrincipal();
			userinfo.put(SecurityConstants.DETAILS_USER_ID, xSnowUser.getId());
			userinfo.put(SecurityConstants.DETAILS_USERNAME, xSnowUser.getUsername());
			userinfo.put(SecurityConstants.DETAILS_EMAIL, xSnowUser.getEmail());
			userinfo.put(SecurityConstants.DETAILS_PHONE, xSnowUser.getPhone());
			userinfo.put(SecurityConstants.DETAILS_TENANT_ID, authentication.getOAuth2Request().getClientId());
			final Map<String, Object> additionalInfo = new HashMap<>(1);
			additionalInfo.put(SecurityConstants.XSNOW_USER,userinfo);

			//其他信息增强
			additionalInfo.put(SecurityConstants.DETAILS_USERNAME,xSnowUser.getUsername());
			additionalInfo.put(SecurityConstants.DETAILS_LICENSE,SecurityConstants.XSNOW_LICENSE);

			((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);

			//其他信息增强
			final Map<String, Object> additional = new HashMap<>(4);
			return accessToken;
		};
	}

}
